package com.doform.android.xianggucheng.activity.library;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.doform.android.xianggucheng.BaseTimePickerActivity;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.adapter.CommonListAdapter;
import com.doform.android.xianggucheng.bean.GuidBean;
import com.doform.android.xianggucheng.bean.InLibraryDetailBean;
import com.doform.android.xianggucheng.bean.LibraryBean2;
import com.doform.android.xianggucheng.bean.QueryLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqAddInLibrary;
import com.doform.android.xianggucheng.bean.request_bean.ReqListLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqSubmitInLibrary;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateInLibrary;
import com.doform.android.xianggucheng.holder.ViewHolder;
import com.doform.android.xianggucheng.popwindow.IPopWindow;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-18.
 * GitHub：https://github.com/cxydxpx
 */

public class InLibraryOrActivity extends BaseTimePickerActivity {

    @BindView(R.id.ll1)
    LinearLayout mLl;

    //    仓库
    @BindView(R.id.rl_library)
    RelativeLayout rl_library;

    @BindView(R.id.tv_library)
    TextView tv_library;
    //    结算方式
    @BindView(R.id.rl_clearType)
    RelativeLayout rl_clearType;

    @BindView(R.id.tv_clearType)
    TextView tv_clearType;

    @BindView(R.id.rl_time)
    RelativeLayout rl_time;

    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.tv_person)
    EditText et_persion;

    @BindView(R.id.et_remark)
    EditText et_remark;

    @BindView(R.id.tv_sum_price)
    TextView tv_sum_price;

    //    结算方式
    private String mClearTypeId;
    private String mClearTypeName;
    //    仓库名称
    private String mLibraryId;
    private String mLibraryName;
    //    结算方式 数据
    private List<String> mClearTypeData = new ArrayList<>();
    //    仓库 数据
    private List<QueryLibraryBean> mLibraryData = new ArrayList<>();

    private String mMoney;

    private IPopWindow mPopupWindow, mPopupWindow2, mPopupWindow3;
    //    s是否已添加商品明细
    private String mId;
    //  为true时才可以提交采购单
    private String mTime;
    private String mPerson;
    private String mRemark;
    private String mGuid;

    @Override
    protected int layoutResId() {
        return R.layout.activity_common_library;
    }

    @Override
    protected void init() {
        super.init();

        LibraryBean2.ListBean bean = (LibraryBean2.ListBean) getIntent().getSerializableExtra(Constans.EXTRA_LIBRARY);

        if (bean != null) {
            mId = bean.getId();
            mGuid = bean.getGuid();
        }

        if (mPopupWindow == null) {
            mPopupWindow = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }

        if (mPopupWindow2 == null) {
            mPopupWindow2 = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }

        if (mPopupWindow3 == null) {
            mPopupWindow3 = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }
    }


    @Override
    protected void initView() {
        super.initView();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        long curTime = System.currentTimeMillis();
        mTime = formatter.format(new Date(curTime));
        tv_time.setText(mTime);
    }

    @Override
    protected void initData() {

        mClearTypeData.add("现金");
        mClearTypeData.add("账期");

        initLibraryData();
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("采购单申请管理");
    }

    @Override
    protected void updateData() {
        super.updateData();
        if (mId != null) {
            HttpManager
                    .instance()
                    .getInLibraryDetail(new ReqQueryLibraryBean(mId))
                    .subscribe(new ErrorHandleSubscriber<ArrayList<InLibraryDetailBean>>() {
                                   @Override
                                   public void onNext(@NonNull ArrayList<InLibraryDetailBean> inLiBraryDetail) {
                                       updateUi(inLiBraryDetail.get(0));
                                   }
                               }
                    );
        } else {
        }

    }

    /**
     * 当修改的时候 进来可直接显示已有的数据
     *
     * @param data
     */
    private void updateUi(InLibraryDetailBean data) {

        switch (data.getMethod()) {
            case "1":
                mClearTypeId = "1";
                mClearTypeName = "现金";
                break;
            case "2":
                mClearTypeId = "2";
                mClearTypeName = "账期";
                break;
        }
        tv_clearType.setText(mClearTypeName);

        mLibraryId = data.getWhid();
        mLibraryName = data.getWhname();
        tv_library.setText(mLibraryName);

        mTime = data.getBuydate();
        tv_time.setText(mTime);

        mPerson = data.getApname();
        et_persion.setText(mPerson);

        mRemark = data.getRemark();
        et_remark.setText(mRemark);

        mMoney = data.getMoney();
        tv_sum_price.setText(mMoney);

    }

    private void beforeCreate() {

        mTime = tv_time.getText().toString().trim();
        mPerson = et_persion.getText().toString().trim();
        mRemark = et_remark.getText().toString().trim();

        if (TextUtils.isEmpty(mClearTypeId)) {
            TsUtils.showToast("请选择结算方式");
            return;
        } else if (TextUtils.isEmpty(mLibraryId)) {
            TsUtils.showToast("请选择仓库");
            return;
        } else if (TextUtils.isEmpty(mTime)) {
            TsUtils.showToast("请选择采购日期");
            return;
        } else if (TextUtils.isEmpty(mPerson)) {
            TsUtils.showToast("请选择采购人");
            return;
        } else if (TextUtils.isEmpty(mRemark)) {
            mRemark = "";
        }


        postDataToService(mClearTypeId, mLibraryId, mLibraryName, mTime, mPerson, mRemark);
    }

    private void postDataToService(String mClearTypeId, String libraryId, String mLibraryName
            , String mTime, String mPerson, String mRemark) {
        HttpManager.instance()
                .addInLibrary(new ReqAddInLibrary(mClearTypeId, libraryId, mLibraryName, mTime, mPerson, mRemark))
                .subscribe(new ErrorHandleSubscriber<GuidBean>() {
                               @Override
                               public void onNext(@NonNull GuidBean bean) {

                                   mId = bean.getId();
                                   mGuid = bean.getGuid();
                                   if (TYPE_GOTO == TYPE_TO) {//
                                       Intent intent = new Intent(InLibraryOrActivity.this, LibraryDetailOrActivity.class);
                                       intent.putExtra(Constans.EXTRA_ADD_LIBRARY_ID, mId);
                                       intent.putExtra(Constans.EXTRA_ADD_LIBRARY_GUID, mGuid);
                                       intent.putExtra(Constans.EXTRA_ADD_LIBRARY_LIBRARY_ID, mLibraryId);
                                       startActivityForResult(intent, Constans.REQUEST_NEW_LIBRARY);
                                   } else if (TYPE_FINISH == TYPE_TO) {
                                       Intent intent = new Intent();
                                       intent.putExtra(Constans.EXTRA_IN_LIBRARY_TYPE, "1");
                                       setResult(Constans.REQUEST_IN_LIBRARY, intent);
                                       finish();
                                   } else {
                                   }
                               }
                           }
                );
    }

    private void showClearTypePop(List<String> datas) {
        mPopupWindow.setHeadName("选择结算方式");

        mPopupWindow.setPopAdapter(new CommonListAdapter<String>(this, datas, R.layout.pop_item) {
                                       @Override
                                       protected void convert(ViewHolder vh, final List<String> datas, final int position) {
                                           final String dataBean = datas.get(position);
                                           final TextView tv = vh.getView(R.id.tv);
                                           tv.setText(dataBean);
                                           vh.getView(R.id.rl_select)
                                                   .setOnClickListener(new View.OnClickListener() {
                                                                           @Override
                                                                           public void onClick(View v) {
                                                                               tv_clearType.setText(dataBean);
                                                                               if (dataBean.equals("现金")) {
                                                                                   mClearTypeId = "1";
                                                                                   mClearTypeName = "现金";
                                                                               } else if (dataBean.equals("账期")) {
                                                                                   mClearTypeId = "2";
                                                                                   mClearTypeName = "账期";
                                                                               } else {
                                                                                   mClearTypeId = "1";
                                                                                   mClearTypeName = "现金";
                                                                               }
                                                                               mPopupWindow.dismiss();
                                                                           }
                                                                       }
                                                   );
                                       }
                                   }
        );
        mPopupWindow.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    private void showLibraryPop(List<QueryLibraryBean> datas) {

        mPopupWindow2.setHeadName("选择仓库");

        mPopupWindow2.setPopAdapter(new CommonListAdapter<QueryLibraryBean>(this, datas, R.layout.pop_item) {
                                        @Override
                                        protected void convert(ViewHolder vh, final List<QueryLibraryBean> datas, final int position) {
                                            final QueryLibraryBean bean = datas.get(position);
                                            final TextView tv = vh.getView(R.id.tv);
                                            tv.setText(bean.getName());
                                            vh.getView(R.id.rl_select)
                                                    .setOnClickListener(new View.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(View v) {
                                                                                mLibraryId = bean.getId();
                                                                                mLibraryName = bean.getName();
                                                                                tv_library.setText(mLibraryName);
                                                                                mPopupWindow2.dismiss();
                                                                            }
                                                                        }
                                                    );
                                        }
                                    }
        );
        mPopupWindow2.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    // 仓库数据
    private void initLibraryData() {
        HttpManager
                .instance()
                .getLibraryQuery(new ReqListLibraryBean())
                .subscribe(new ErrorHandleSubscriber<ArrayList<QueryLibraryBean>>() {
                               @Override
                               public void onNext(@NonNull ArrayList<QueryLibraryBean> libraryBean) {
                                   parseLibrary(libraryBean);
                               }
                           }
                );
    }

    private void parseLibrary(@NonNull ArrayList<QueryLibraryBean> libraryBean) {
        mLibraryData.addAll(libraryBean);
        if (mLibraryData.size() == 1){
            mLibraryId = mLibraryData.get(0).getId();
             mLibraryName = mLibraryData.get(0).getName();
            tv_library.setText(mLibraryName);
        }
    }

    /**
     * 保存采购单
     */
    private void beForeSave() {
        String mTime = tv_time.getText().toString().trim();
        String mPerson = et_persion.getText().toString().trim();
        String mRemark = et_remark.getText().toString().trim();
        if (TextUtils.isEmpty(mClearTypeId)) {
            TsUtils.showToast("请选择结算方式");
            return;
        } else if (TextUtils.isEmpty(mLibraryId)) {
            TsUtils.showToast("请选择仓库");
            return;
        }  else if (TextUtils.isEmpty(mTime)) {
            TsUtils.showToast("请选择采购日期");
            return;
        } else if (TextUtils.isEmpty(mPerson)) {
            TsUtils.showToast("请选择采购人");
            return;
        }
        updateDataToService(mId, mGuid, mLibraryId, mLibraryName, mClearTypeId, mTime, mPerson, mRemark);
    }

    /**
     * 保存采购单
     *
     * @param id
     * @param mLibraryId
     * @param mLibraryName
     * @param mClearTypeId
     * @param mTime
     * @param mPerson
     * @param mRemark
     */
    private void updateDataToService(final String id, final String guid, final String mLibraryId, String mLibraryName, String mClearTypeId,
                                     String mTime, String mPerson, String mRemark) {
        HttpManager
                .instance()
                .updateInLibrary(new ReqUpdateInLibrary(id, guid, mLibraryId, mLibraryName, mClearTypeId, mTime, mPerson, mRemark,"1"))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                               @Override
                               public void onNext(@NonNull Integer num) {
                                   mId = id;
                                   mGuid = guid;
                                   if (TYPE_GOTO == TYPE_TO) {//
                                       Intent intent = new Intent(InLibraryOrActivity.this, LibraryDetailOrActivity.class);
                                       intent.putExtra(Constans.EXTRA_ADD_LIBRARY_ID, mId);
                                       intent.putExtra(Constans.EXTRA_ADD_LIBRARY_GUID, mGuid);
                                       intent.putExtra(Constans.EXTRA_ADD_LIBRARY_LIBRARY_ID, mLibraryId);
                                       startActivityForResult(intent, Constans.REQUEST_NEW_LIBRARY);
                                   } else if (TYPE_FINISH == TYPE_TO) {
                                       Intent intent = new Intent();
                                       intent.putExtra(Constans.EXTRA_IN_LIBRARY_TYPE, "1");
                                       setResult(Constans.REQUEST_IN_LIBRARY, intent);
                                       finish();
                                   } else {
                                   }

                               }
                           }
                );
    }

    /**
     * 提交采购入库订单
     *
     * @param mId
     */
    private void beforeSubmit(String mId) {

        String mTime = tv_time.getText().toString().trim();
        String mPerson = et_persion.getText().toString().trim();
        String mRemark = et_persion.getText().toString().trim();
        if (TextUtils.isEmpty(mClearTypeId)) {
            TsUtils.showToast("请选择结算方式");
            return;
        } else if (TextUtils.isEmpty(mLibraryId)) {
            TsUtils.showToast("请选择仓库");
            return;
        } else if (TextUtils.isEmpty(mTime)) {
            TsUtils.showToast("请选择采购日期");
            return;
        } else if (TextUtils.isEmpty(mPerson)) {
            TsUtils.showToast("请选择采购人");
            return;
        } else if (TextUtils.isEmpty(mMoney) || Double.parseDouble(mMoney) < 1) {
            TsUtils.showToast("请添加采购明细");
            return;
        }
        submittDataToService(mId, mGuid, mLibraryId, mLibraryName, mTime, mPerson, mRemark, mClearTypeId);
    }

    /**
     * @param mId
     * @param mGuid
     * @param mLibraryId
     * @param mLibraryName
     * @param mTime
     * @param mPerson
     * @param mRemark
     * @param mClearTypeId
     */
    private void submittDataToService(String mId, String mGuid, String mLibraryId, String mLibraryName,
                                      String mTime, String mPerson,
                                      String mRemark, String mClearTypeId) {
        HttpManager
                .instance()
                .submitInLibrary(new ReqSubmitInLibrary(mId, mGuid, mLibraryId, mLibraryName, mTime, mPerson, mRemark, mClearTypeId))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                               @Override
                               public void onNext(@NonNull Integer num) {
                                   Intent intent = new Intent();
                                   intent.putExtra(Constans.EXTRA_IN_LIBRARY_TYPE, "5");
                                   setResult(Constans.REQUEST_IN_LIBRARY, intent);
                                   finish();
                               }
                           }
                );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Constans.REQUEST_NEW_LIBRARY:
                if (null != data) {
                    String Id = data.getStringExtra("applyid");
                    this.mId = Id;
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void finish() {
        super.finish();
        mId = null;
    }

    private final int TYPE_GOTO = 1;
    private final int TYPE_FINISH = 2;
    private int TYPE_TO = 0;


    @OnClick({R.id.rl_go, R.id.btn_submit, R.id.rl_clearType, R.id.rl_library, R.id.rl_time, R.id.btn_save, R.id.rl_back})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                Intent intent = new Intent();
                intent.putExtra(Constans.EXTRA_IN_LIBRARY_TYPE, "1");
                setResult(Constans.REQUEST_IN_LIBRARY, intent);
                finish();
                break;
            case R.id.btn_save://当mID不为空的时候 才会去创建
                if (TextUtils.isEmpty(mId)) {
                    beforeCreate();
                } else {
                    beForeSave();
                }
                TYPE_TO = TYPE_FINISH;
                break;
            case R.id.rl_go:
                if (TextUtils.isEmpty(mId)) {
                    beforeCreate();
                } else {
                    beForeSave();
                }
                TYPE_TO = TYPE_GOTO;
                break;
            case R.id.btn_submit:
                beforeSubmit(mId);
                break;
            case R.id.rl_clearType://结算方式
                showClearTypePop(mClearTypeData);
                break;
            case R.id.rl_library://仓库
                showLibraryPop(mLibraryData);
                break;
            case R.id.rl_time:
                if (pvTime != null) {
                    pvTime.show(tv_time);
                }
                break;
            default:
                break;
        }
    }
}
